package com.congee02.dbservlet.framework.jdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

public final class JdbcTemplateFactory {

    private JdbcTemplateFactory() {}

    /**
     * 从 Properties 文件读取配置获取 {@link JdbcTemplate}
     */
    public static JdbcTemplate getJdbcTemplateFromPropertiesFile(String filename) throws IOException {
        return getJdbcTemplateFromPropertiesStream(
                new FileInputStream(
                        Objects.requireNonNull(JdbcTemplateFactory.class.getClassLoader().getResource(filename)).getPath()
                )
        );
    }

    /**
     * 从 Properties 文件流读取配置获取 {@link JdbcTemplate}
     */
    public static JdbcTemplate getJdbcTemplateFromPropertiesStream(InputStream stream) throws IOException {
        Properties configProperties = new Properties();
        try (InputStream ignored = stream) {
            configProperties.load(stream);
        }
        return new JdbcTemplate(
                requireNotNullNotBlankReadProperties(configProperties, "name"),
                requireNotNullNotBlankReadProperties(configProperties, "driverClassName"),
                requireNotNullNotBlankReadProperties(configProperties, "url"),
                requireNotNullNotBlankReadProperties(configProperties, "username"),
                requireNotNullNotBlankReadProperties(configProperties, "password"),
                requireNotNullNotBlankReadProperties(configProperties, "coreSize"),
                requireNotNullNotBlankReadProperties(configProperties, "maxSize")
        );
    }


    /**
     * 从 Properties 文件或者流中读取配置，保证每个配置不为空
     */
    private static String requireNotNullNotBlankReadProperties(Properties configProperties, String property) {
        String value = Objects.requireNonNull(configProperties.getProperty(property));
        if (value.isBlank()) {
            throw new NullPointerException(property + "字段配置为空");
        }
        return value;
    }

}
